import request from '@/utils/request';
import { ElMessage } from 'element-plus'
import router from '@/router';
export default ({
    state: {
        id:'',
        username:'',
        photo:'',
        phone:'',
        role:'',
        token:'',
        status:'',
        isLogin:false,
        loginTime:''
    },
    getters: {
    },
    mutations: {
        getLoginUser(state,user){
            state.id = user.id;
            state.username = user.username;
            state.photo = user.photo;
            state.phone = user.phone;
            state.role = user.role;
            state.status = user.status;
            state.isLogin = true;
            state.loginTime = user.loginTime
        },
        getToken(state,token){
            state.token = token;
        },
        Logout(state){
            state.id = '';
            state.username = '';
            state.photo = '';
            state.isLogin = false;
        }
    },
    actions: {
        // 登录请求获取token
        login(context,data){
            request({
                url:'/user/token/',
                method:'post',
                data:JSON.stringify({
                    username:data.username,
                    password:data.password
                })
            }).then(function(response){
                if(response.message === 'success'){
                    localStorage.setItem('jwt_token',response.token);
                    context.commit('getToken',response.token);
                    context.dispatch('getUserInfo');
                }else{
                    ElMessage({message: '用户名或密码错误!',grouping: true,type: 'error',})
                }
            }).catch(function(){
                ElMessage({message: '用户名或密码错误!',grouping: true,type: 'error',})
            })
        },
        // 根据token获取登录用户信息
        getUserInfo(context){
            request({
                url:'/user/info/',
                method:'post',
                headers:{
                    Authorization:"Bearer "+context.state.token,
                }
            }).then(function(resp){
                if(resp.status === 'stop'){
                    ElMessage({message: '用户已被禁用！请联系管理员！',grouping: true, type: 'error'})
                }else if(resp.status === 'normal'){
                    context.commit('getLoginUser',{...resp});
                    ElMessage({message: '登录成功!',type: 'success',})
                    router.push('/');
                }
            }).catch(function(resp){
                console.log(resp)
                ElMessage({message: '用户状态过期，请重新登录!',grouping: true,type: 'warning',})
            })
        }
    },
    modules:{
    }
})